import type { FormSchema } from '@/components/core/schema-form/';
import Upload from "@/components/basic/upload/index.vue";
import { h } from 'vue';

export interface KnowledgeFileDto {
  id?: string;
  knowledgeBaseId: string;
  fileMD5: string;
  fileName: string;
  suffix: string;
  size: number;
  sliceType: number; // 切片方式
  fixedLength?: number; // 固定长度大小
  isEmbedding?: boolean; // 是否已向量化
}

// 定义一个表单上下文对象，用于存储和访问表单模型
export const formContext = {
  model: null as KnowledgeFileDto | null,
  // 设置文件信息到表单模型
  setFileInfo(fileInfo: any) {
    if (this.model && fileInfo) {
      this.model.fileName = fileInfo.fileName || '';
      this.model.suffix = fileInfo.suffix || '';
      this.model.size = fileInfo.size || 0;
    }
  }
};

export const baseSchemas: FormSchema<KnowledgeFileDto>[] = [
  {
    field: 'knowledgeBaseId',
    component: 'Select',
    label: '所属知识库',
    required: true,
    componentProps: {
      placeholder: '请选择所属知识库',
    },
  },
  {
    field: 'sliceType',
    component: 'DictSelect',
    label: '切片方式',
    required: true,
    defaultValue: 0,
    componentProps: {
      placeholder: '请选择切片方式',
      dictCode: 'slice_type',
      valueType: 'number',
    },
  },
  {
    field: 'fixedLength',
    component: 'InputNumber',
    label: '固定长度大小',
    required: true,
    defaultValue: 500,
    componentProps: {
      placeholder: '请输入固定长度大小',
      min: 1,
    },
    vIf: ({ formModel }) => formModel.sliceType === 0,
  },
  {
    field: 'fileMD5',
    component: ({ formModel, formInstance }) => {
      // 保存表单模型引用
      formContext.model = formModel;
      
      return h(Upload, {
        modelValue: formModel.fileMD5,
        'onUpdate:modelValue': (val: string) => {
          formModel.fileMD5 = val;
          // 当值更新后，手动触发验证以清除错误提示
          if (val) {
            setTimeout(() => {
              formInstance?.validateFields(['fileMD5']);
            }, 100);
          }
        },
        onFileInfo: (fileInfo: any) => {
          console.log('文件信息回调:', fileInfo);
          formContext.setFileInfo(fileInfo);
        }
      });
    },
    label: '上传文件',
    required: true,
    helpMessage: '请上传文件',
    rules: [
      {
        required: true,
        message: '请上传文件',
        validator: (_, value) => {
          if (!value) {
            return Promise.reject('请上传文件');
          }
          return Promise.resolve();
        }
      }
    ]
  },
  // 以下字段在表单中隐藏，由上传组件自动填充
  {
    field: 'fileName',
    component: 'Input',
    label: '文件名',
    vShow: false,
  },
  {
    field: 'suffix',
    component: 'Input',
    label: '文件后缀',
    vShow: false,
  },
  {
    field: 'size',
    component: 'InputNumber',
    label: '文件大小(KB)',
    vShow: false,
  },
]; 